import { defineStore } from "pinia";
import router from "@/router";
import { UtilTool } from "@webxue/common";
import { useUserStore } from "@/stores/user.store";

export const useMenuStore = defineStore("menuStore", {
  state: () => ({}),
  getters: {
    // 获取扁平化菜单
    getFlatUserMenu(): any[] {
      return UtilTool.flatArr(useUserStore().userMenus, "children");
    },
    // 根据当前url及参数匹配对应菜单
    getRouteMenu(): any {
      // 创建URL对象
      const routePathUrl = new URL(router.currentRoute.value.fullPath, location.origin);

      return useMenuStore().getFlatUserMenu.find((menu: any) => {
        const parsedMenuUrl = new URL(menu.menuUrl, location.origin);
        if (parsedMenuUrl.pathname !== routePathUrl.pathname) return false;

        const routePathParams = new URLSearchParams(routePathUrl.search) as any;
        const parsedMenuUrlParams = new URLSearchParams(parsedMenuUrl.search) as any;

        // 遍历menuUrl的所有参数
        for (const [key, value] of routePathParams.entries()) {
          // 如果第二个URL中不存在相同的键或者值不匹配，则返回false
          if (parsedMenuUrlParams.get(key) !== value) {
            return false;
          }
        }

        // 如果所有检查都通过，则返回true表示找到匹配项
        return true;
      });
    },
    // 获取主页
    getDashboard() {
      return useMenuStore().getFlatUserMenu.filter((menu:any) => menu.path)[0] || {}
    }
  },
  actions: {}
});
